import { NextResponse, type NextRequest } from 'next/server';
import { redirectToLogin } from '@/utils/back/redirect';

const allowedOrigins = [] as string[];

const corsOptions = {
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers':
    'Content-Type, Authorization, Content-Length, X-APP-Secret',
  'Access-Control-Allow-Credentials': 'true',
};

export async function middleware(request: NextRequest, ...args: any[]) {
  // console.log('[middleware]: ', request.method, request.url);

  const pathname = request.nextUrl.pathname;
  const isProductDetailPage = pathname.startsWith('/product/');
  const isBlogPage = pathname.startsWith('/blog');
  const isDstheme = pathname.startsWith('/dstheme/');
  const isApiRequest = pathname.startsWith('/api/');

  // reverse proxy
  if (isBlogPage || isDstheme) {
    const targetUrl = request.nextUrl.href.replace(
      /^(https?:)?\/\/[^/]*/,
      process.env.NEXT_PUBLIC_DSZ_DOMAIN_PROD!
    );
    return NextResponse.rewrite(new URL(targetUrl));
  }

  const oUrl = new URL(request.url);
  const shouldSkipToken = oUrl.pathname.startsWith('/api/login');

  const origin = request.headers.get('origin') ?? '';
  const needCheckOrigin = allowedOrigins.length > 0;
  const isAllowedOrigin = !needCheckOrigin || allowedOrigins.includes(origin!);
  if (!isAllowedOrigin) {
    return new Response('Not allowed', { status: 403 });
  }

  const isPreflight = request.method === 'OPTIONS';
  if (isPreflight) {
    return new Response(null, {
      status: 204,
      headers: Object.assign(
        { 'Access-Control-Allow-Origin': origin },
        corsOptions
      ),
    });
  }

  const getResponse = (userId = '') => {
    const headers = new Headers(request.headers);
    headers.set('userid', userId);

    const response = NextResponse.next({
      request: {
        ...request,
        headers: headers,
      },
    });

    if (isAllowedOrigin) {
      response.headers.set('Access-Control-Allow-Origin', origin);
    }

    Object.entries(corsOptions).forEach(([key, value]) => {
      response.headers.set(key, value);
    });

    return response;
  };

  if (shouldSkipToken) {
    return getResponse();
  }

  //   @ts-ignore
  const token = request.cookies.get('token')?.value ?? '';

  if (!token) {
    if (isApiRequest) {
      return new NextResponse(
        JSON.stringify({
          success: false,
          message: 'Unauthorized',
          data: { token },
        }),
        {
          status: 401,
          headers: Object.assign(
            { 'Access-Control-Allow-Origin': origin },
            corsOptions
          ),
        }
      );
    } else {
      if (isProductDetailPage) {
        return redirectToLogin(request.url);
      } else {
        // todo
        return redirectToLogin(request.url);
      }
    }

    // return NextResponse.json({
    //   success: false,
    //   message: "Unauthorized",
    //   data: { token },
    // });
  }

  return getResponse('Alice');

  // request.headers.set("x-user", userId);

  // NextResponse.next(request);
}

export const config = {
  matcher: [
    // '/api/((?!login|logout|image|author|redirect|error|front/catalogsearch).*)',
    '/api/front/v2/product/detail',
    '/product/:path*',
    '/blog($|/.*)',
    '/dstheme/:path*',
  ],
};
